package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.ResponseResult;
import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/searchUserServlet")
public class SearchUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //去除中文乱码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //调用业务层的方法拿到所有数据库的用户数据
        List<User> userList = new UserService().findAllUser();

        //创建响应数据的对象
        ResponseResult<User> result = new ResponseResult<User>("ok",200,userList);

        //将数据转换成json格式的字符串返回给浏览器
        String json = JSON.toJSONString(result);

        //将数据响应给浏览器
        response.getWriter().print(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
